<template>
<div class="submit-container">
    <header-component />
    <div class="submit-content">
        <div class="submit-header">
            <h1>提交网站</h1>
            <div class="divider"></div>
            <p class="submit-desc">欢迎提交优质网站，共同丰富伴福熊导航资源库。我们会在审核通过后将您提交的网站添加到相应频道。</p>
        </div>

        <el-card class="submit-card">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="submit-form">

                <el-form-item label="所属频道" prop="channelId">
                    <el-select v-model="form.channelId" placeholder="请选择所属频道" style="width: 100%;">
                        <el-option v-for="channel in channels" :key="channel.id" :label="channel.name"
                            :value="channel.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="网站名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入网站名称"></el-input>
                </el-form-item>

                <el-form-item label="网站地址" prop="url">
                    <div class="url-input-container">
                        <el-input v-model="form.url" placeholder="请输入网站地址，以http://或https://开头"></el-input>
                        <el-button type="primary" :disabled="!form.url" @click="getTDK">获取TDK</el-button>
                    </div>
                </el-form-item>

                <!-- <el-form-item label="网站图标" prop="icon">
                    <el-upload class="icon-uploader" action="#" :http-request="handleIconUpload" :show-file-list="false"
                        :before-upload="beforeIconUpload">
                        <img v-if="form.icon" :src="form.icon" class="icon-preview">
                        <i v-else class="el-icon-plus icon-uploader-icon"></i>
                        <div class="el-upload__tip">请上传网站图标，只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item> -->

                <el-form-item label="网站描述" prop="description">
                    <el-input type="textarea" v-model="form.description" :rows="4"
                        placeholder="请简要描述网站的主要内容和特点"></el-input>
                </el-form-item>

                <el-form-item label="联系邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入您的联系邮箱，方便我们与您沟通"></el-input>
                </el-form-item>

                <el-form-item label="验证码" prop="captchaCode">
                    <div class="captcha-container">
                        <el-input v-model="form.captchaCode" maxlength="4" minlength="4" placeholder="请输入验证码"
                            class="captcha-input"></el-input>
                        <div class="captcha-image-div" @click="getCode"><img :src="codeUrl" class="captcha-image"
                                @click="getCode" /></div>
                    </div>
                </el-form-item>

                <el-form-item class="submit-buttons">
                    <el-button type="primary" @click="submitForm('form')">提交网站</el-button>
                    <el-button @click="resetForm('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
    <footer-component />
    <back-to-top :visibilityHeight="100" />
</div>
</template>

<script>
import HeaderComponent from '@/components/Header.vue'
import FooterComponent from '@/components/Footer.vue'
import BackToTop from '@/components/BackToTop.vue'
import { getCodeImg, getChannels, addWebsitesByChannel, getTDK } from '@/api/index'

export default {
    name: 'SubmitPage',
    components: {
        HeaderComponent,
        FooterComponent,
        BackToTop
    },
    data() {
        // URL验证规则
        const validateUrl = (rule, value, callback) => {
            if (value && !/^https?:\/\/.+/.test(value)) {
                callback(new Error('请输入以http://或https://开头的有效网址'))
            } else {
                callback()
            }
        }

        return {
            channels: [
                { id: 0, name: '无' },
            ],
            codeUrl: '',
            form: {
                name: '',
                url: '',
                icon: '',
                channelId: 0,
                description: '',
                email: '',
                captchaCode: '',
                uuid: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入网站名称', trigger: 'blur' },
                    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入网站地址', trigger: 'blur' },
                    { validator: validateUrl, trigger: 'blur' }
                ],
                channelId: [
                    { required: true, message: '请选择所属频道', trigger: 'change' }
                ],
                description: [
                    { required: true, message: '请输入网站描述', trigger: 'blur' },
                    { min: 10, max: 200, message: '长度在 10 到 200 个字符', trigger: 'blur' }
                ],
                captchaCode: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { min: 4, max: 4, message: '验证码长度不正确', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getCode();
        this.fetchChannels()
    },
    methods: {
        getCode() {
            getCodeImg().then(res => {
                this.codeUrl = "data:image/gif;base64," + res.img;
                this.form.uuid = res.uuid;
            });
        },
        // 获取频道列表
        fetchChannels() {
            getChannels().then(response => {
                this.channels = response.data
            }).catch(error => {
                console.error('获取频道列表失败:', error)
                this.$message.error('获取频道列表失败，请刷新页面重试')
            })
        },

        // 图标上传前的验证
        beforeIconUpload(file) {
            const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
            const isLt500K = file.size / 1024 < 500

            if (!isJPGOrPNG) {
                this.$message.error('图标只能是 JPG 或 PNG 格式!')
            }
            if (!isLt500K) {
                this.$message.error('图标大小不能超过 500KB!')
            }
            return isJPGOrPNG && isLt500K
        },

        // 处理图标上传
        handleIconUpload(options) {
            // 这里模拟上传，实际项目中应该调用上传API·
            const file = options.file
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                this.form.icon = reader.result
            }
        },
        // 提交表单
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 实际项目中应该调用提交网站的API
                    addWebsitesByChannel(this.form).then(() => {
                        this.$message({
                            message: '网站提交成功，我们会尽快审核！',
                            type: 'success'
                        })
                        this.resetForm(formName)
                        this.getCode();
                    }).catch(error => {
                        console.error('网站提交失败:', error)
                        // this.$message.error('获取频道列表失败，请刷新页面重试')
                    })
                } else {
                    return false
                }
            })
        },

        // 重置表单
        resetForm(formName) {
            const oldChannelId = this.form.channelId
            this.$refs[formName].resetFields()
            this.form.icon = ''
            this.form.channelId = oldChannelId
        },

        // 获取网站TDK信息
        getTDK() {
            if (!this.form.url) {
                this.$message.warning('请先输入网站地址')
                return
            }
            // this.$message.info('')

            const loading = this.$loading({
                lock: true,
                text: '正在获取网站信息，请稍候...',
                spinner: 'el-icon-loading',
            });
            // 调用获取TDK的API
            getTDK(this.form.url).then(response => {
                if (response && response.data) {
                    const { title, description, icon } = response.data
                    // 自动填充表单
                    if (title) this.form.name = title
                    if (description) this.form.description = description
                    if (icon) this.form.icon = icon
                    this.$message.success('网站信息获取成功')
                    loading.close();
                }
            }).catch(error => {
                console.error('获取网站TDK失败:', error)
                // this.$message.error('获取网站信息失败，请检查网址是否正确')
                loading.close();
            })
        }
    }
}
</script>

<style scoped>
.submit-container {
    min-height: 100vh;
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
    /* 为固定Header留出空间 */
}

.fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1000;
}

.submit-content {
    max-width: 800px;
    margin: 0 auto;
    padding: 30px 20px;
    flex: 1;
    width: 100%;
    /* 确保内容占满容器宽度 */
    box-sizing: border-box;
    /* 确保padding不会增加宽度 */
}

.submit-header {
    text-align: center;
    margin-bottom: 30px;
}

.submit-header h1 {
    font-size: 28px;
    color: #303133;
    margin-bottom: 15px;
}

.submit-desc {
    color: #606266;
    margin-top: 15px;
    font-size: 16px;
    line-height: 1.6;
}

.divider {
    height: 3px;
    width: 60px;
    background-color: #409EFF;
    margin: 0 auto;
}

.submit-card {
    margin-bottom: 30px;
    border-radius: 8px;
}

.submit-form {
    padding: 20px 0;
}

.url-input-container {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    /* 允许在小屏幕上折行 */
}

.url-input-container .el-input {
    flex: 1;
    min-width: 200px;
    /* 确保输入框有最小宽度 */
}

.icon-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.icon-uploader .el-upload:hover {
    border-color: #409EFF;
}

.icon-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
}

.icon-preview {
    width: 80px;
    height: 80px;
    display: block;
}

.captcha-container {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    /* 确保不换行 */
    gap: 10px;
}

.captcha-input {
    flex: 1;
    min-width: 120px;
    max-width: 150px;
}

.captcha-image-div {
    width: 75px;
    height: 40px;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #606266;
    cursor: pointer;
    border-radius: 4px;
    flex-shrink: 0;
    /* 防止图片被压缩 */
}

.captcha-image {
    width: 75px;
    height: 40px;
}

.submit-buttons {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.submit-buttons .el-button {
    margin: 0 10px;
}

@media (max-width: 768px) {
    .submit-content {
        padding: 20px 15px;
    }

    .submit-form {
        padding: 10px 0;
    }

    /* 移动端表单标签调整 */
    ::v-deep .el-form-item__label {
        text-align: left;
        float: none;
        display: block;
        padding: 0 0 10px 0;
    }


    ::v-deep .el-form-item__content {
        margin-left: 0 !important;
    }

    .submit-form {

        /* 去掉label宽度限制 */
        ::v-deep .el-form-item {
            display: flex;
            flex-direction: column;
        }
    }

    .submit-header h1 {
        font-size: 24px;
    }

    .submit-desc {
        font-size: 14px;
    }

    .submit-buttons {
        flex-direction: column;
        align-items: center;
    }

    .submit-buttons .el-button {
        margin: 5px 0;
        width: 80%;
    }
}

@media (max-width: 480px) {
    .submit-content {
        padding: 15px 10px;
    }

    .submit-header h1 {
        font-size: 22px;
    }

    .captcha-container {
        flex-direction: row;
        /* 确保在超小屏幕上也是水平排列 */
        align-items: center;
        width: 100%;
    }

    .captcha-input {
        max-width: none;
        width: calc(100% - 85px);
        /* 留出验证码图片的宽度和间距 */
    }
}
</style>